package com.jd.finance.core.controller.admin;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.assist.ISqlRunner;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jd.finance.core.config.URLConst;
import com.jd.finance.core.mapper.ProductMapper;
import com.jd.finance.core.mapper.UserMapper;
import com.jd.finance.core.pojo.dto.GetOverDueDTO;
import com.jd.finance.core.pojo.dto.GetRepayRecordDTO;
import com.jd.finance.core.pojo.dto.GetRepayStatusDTO;
import com.jd.finance.core.pojo.entity.Product;
import com.jd.finance.core.service.LoanService;
import com.jd.finance.core.service.impl.AdminUtilsServiceImpl;
import com.jd.finance.result.BaseResult;
import com.jd.finance.util.HttpUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.jd.finance.core.config.URLConst.GET_REPAU_STATUS;

@Api(tags = "数据管理")
@Slf4j
@RestController
@RequestMapping("admin/core/adminMdCenter")
public class adminMdController {

    @Resource
    private AdminUtilsServiceImpl adminUtilsService;
    @Resource
    private LoanService loanService;
    @Resource
    private ProductMapper productMapper;

    @ApiOperation("查询年度流水按月")
    @GetMapping("/getRunWater")
    public BaseResult getRunWater(Integer uid, HttpServletRequest request) {
        if (uid == null) {
            log.error("id为空");
            return BaseResult.error().message("id为空");
        }
        if (adminUtilsService.isGM(uid)) {
            log.error("无访问权限");
            return BaseResult.ok().message("无访问权限");
        }

        return loanService.getRunWater(uid, request);

    }

    @ApiOperation("根据前台用户身份证号，获取所有还款记录信息")
    @GetMapping("/getRepayInfoByIdNo")
    public BaseResult getRepayInfoByIdNo(Integer uid, String idNo) {
        if (uid == null) {
            log.error("id为空");
            return BaseResult.error().message("id为空");
        }
        if (StringUtils.isBlank(idNo)) {
            log.error("idNo为空");
            return BaseResult.error().message("idNo为空");
        }
        if (adminUtilsService.isGM(uid)) {
            log.error("无访问权限");
            return BaseResult.ok().message("无访问权限");
        }
        //封装post数据
        StringBuilder postData = new StringBuilder("idNo=" + idNo);
        log.info(String.format("--> 发送请求到web：post data %1s", postData));

        byte[] bytes1 = postData.toString().getBytes(StandardCharsets.UTF_8);
        byte[] result = HttpUtils.doPost(URLConst.GET_USER_REPAY_INFO_URL, bytes1);
        String s = new String(result);
        log.info(String.format("--> web应答结果：result data %1s", s));
        List<GetRepayRecordDTO> overDueList = JSONArray.parseArray(s, GetRepayRecordDTO.class);

        return BaseResult.ok().data("data", overDueList);

    }

    @ApiOperation("根据前台用户身份证号，获取所有逾期记录")
    @GetMapping("/getOverdueInfoByIdNo")
    public BaseResult getOverdueInfoByIdNo(Integer uid, String idNo) {
        if (uid == null) {
            log.error("id为空");
            return BaseResult.error().message("id为空");
        }
        if (StringUtils.isBlank(idNo)) {
            log.error("idNo为空");
            return BaseResult.error().message("idNo为空");
        }
        if (adminUtilsService.isGM(uid)) {
            log.error("无访问权限");
            return BaseResult.ok().message("无访问权限");
        }
        //封装post数据
        StringBuilder postData = new StringBuilder("idNo=" + idNo);
        log.info(String.format("--> 发送请求到web：post data %1s", postData));

        byte[] bytes1 = postData.toString().getBytes(StandardCharsets.UTF_8);
        byte[] result = HttpUtils.doPost(URLConst.GET_OVER_USER_URL, bytes1);

        String s = new String(result);
        List<GetOverDueDTO> overDueList = JSONArray.parseArray(s, GetOverDueDTO.class);
        for (GetOverDueDTO getOverDueDTO : overDueList) {
            String proName = getOverDueDTO.getCpName();
            QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("pro_name", proName);
            Product product = productMapper.selectOne(queryWrapper);
            getOverDueDTO.setPid(product.getPid());
        }
        log.info(String.format("--> web应答结果：result data %1s", overDueList));
        return BaseResult.ok().data("data", overDueList);
    }

    @ApiOperation("获取所有贷款当月还款状态")
    @GetMapping("/getRepayStatus/{page}/{limit}/{uid}")
    public BaseResult getRepayStatus(
            @ApiParam(value = "当前页码", required = true)
            @PathVariable Long page,

            @ApiParam(value = "每页记录数", required = true)
            @PathVariable Long limit,

            @ApiParam(value = "查询操作的uid", required = true)
            @PathVariable Integer uid) {
        if (uid == null) {
            log.error("id为空");
            return BaseResult.error().message("id为空");
        }
        if (adminUtilsService.isGM(uid)) {
            log.error("无访问权限");
            return BaseResult.ok().message("无访问权限");
        }

        //放入参数
        HashMap<String, Object> paraMap = new HashMap<>();
        paraMap.put("page", page);
        paraMap.put("limit", limit);
        //封装 post 参数 到路径
        StringBuilder postData = new StringBuilder();
        for (Map.Entry<String, Object> param : paraMap.entrySet()) {
            postData.append(param.getKey()).append("=")
                    .append(param.getValue()).append("&");
        }

        log.info(String.format("--> 发送请求到web：post data %1s", postData));

        byte[] bytes1 = postData.toString().getBytes(StandardCharsets.UTF_8);
        byte[] result = HttpUtils.doPost(GET_REPAU_STATUS, bytes1);

        String s = new String(result);

        //将返回json数据转换为实体类
        List<GetRepayStatusDTO> getRepayStatusDTOList = JSONArray.parseArray(s, GetRepayStatusDTO.class);

        log.info(String.format("--> web应答结果：result data %1s", getRepayStatusDTOList));
        return BaseResult.ok().data("data", getRepayStatusDTOList);


    }
}
